package ecweb.ui.order;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ecweb.domain.User;
import ecweb.domain.dto.TOrderDetail;
import ecweb.exception.DatabaseException;
import ecweb.service.IOrderService;
import ecweb.service.impl.OrderService;

/**
 * Servlet implementation class ShowOrderDetailServlet
 */
@WebServlet("/Order/ShowOrderDetail")
public class ShowOrderDetailServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private IOrderService orderService = new OrderService();
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ShowOrderDetailServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		
		User user = (User) session.getAttribute("user");
		if (user == null) {
			response.sendRedirect(request.getContextPath() + "/Account/Login");
			return;
		}
		
		String strId = request.getParameter("id");
		long id = 0;
		try {
			id = Long.parseLong(strId);
		} catch (NumberFormatException e) {
			response.sendError(404);
			return;
		}
		
		TOrderDetail orderDetail = null;
		try {
			orderDetail = orderService.getOrderDetailById(id);
		} catch (DatabaseException e) {
			response.sendError(500);
			return;
		}
		
		if (orderDetail == null) {
			response.sendError(404);
			return;
		}
		
		if (orderDetail.getOrderInfo().getUserId() != user.getId()) {
			response.sendError(404);
			return;
		}
		
		request.setAttribute("order", orderDetail);
		request.getRequestDispatcher("show_order_detail.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

}
